package com.travel.server.manager.impl.dal;

import com.travel.common.CommonConstant;
import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.server.manager.dao.AdvertisingSourceInfoDao;
import com.travel.server.manager.model.AdvertisingSourceInfo;
import com.travel.server.manager.model.AdvertisingSourceInfoExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/12/20 14:49
 * @Desc:
 */
@Component
@Slf4j
public class SourceDal {

    @Autowired
    private AdvertisingSourceInfoDao dao;

    public PageDto<AdvertisingSourceInfo> selectByPage(Integer offset, Integer limit){
        AdvertisingSourceInfoExample example = new AdvertisingSourceInfoExample();
        AdvertisingSourceInfoExample.Criteria criteria = example.or();
        criteria.andStateEqualTo(CommonConstant.YES);
        Integer total = dao.countByExample(example);
        example.setOffset(offset);
        example.setLimit(limit);
        example.setOrderByClause("update_time desc");
        List<AdvertisingSourceInfo> list = dao.selectByExample(example);
        return new PageDto<>(list, total);
    }

    public AdvertisingSourceInfo selectById(Integer id){
        AdvertisingSourceInfo info = dao.selectByPrimaryKey(id);
        if(info == null){
            log.info("not find AdvertisingSourceInfo, id {}", id);
            throw new WorkException(WorkCode.RECORD_NOT_EXIST);
        }
        return info;
    }

    public void insertOrUpdate(AdvertisingSourceInfo advertisingSourceInfo){
        if(advertisingSourceInfo.getId() == null){
            dao.insertSelective(advertisingSourceInfo);
        }else{
            dao.updateByPrimaryKey(advertisingSourceInfo);
        }
    }

    public Integer selectByPositionId(Integer positionId){
        AdvertisingSourceInfoExample example = new AdvertisingSourceInfoExample();
        AdvertisingSourceInfoExample.Criteria criteria = example.or();
        criteria.andPositionIdEqualTo(positionId);
        criteria.andStateEqualTo(CommonConstant.YES);
        return dao.countByExample(example);
    }
}
